package com.game.logic.map;

import com.coment.po.Game;
import com.game.dao.core.GameDao;
import com.game.framework.lock.LooksManager;
import com.game.framework.SpringManager;
import com.xs.build.server.websocket.channel.ClientManager;
import com.xs.build.server.websocket.channel.PushGroup;
import lombok.EqualsAndHashCode;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class PVPService {
    private static final String TAG = "PVP";

    private static final GameDao gameDao = SpringManager.getInstance().getBean(GameDao.class);
    ///
    public static final Map<Integer, PVP> PVPInfoData = new ConcurrentHashMap<>();

    public static void startBattle(Integer anchorInfoId1, Integer anchorInfoId2) {
        String string1 = ClientManager.clientIdMap.get(anchorInfoId1.toString());
        String string2 = ClientManager.clientIdMap.get(anchorInfoId2.toString());

        ClientManager.joinTag(PushGroup.GAME_GROUP, string1, TAG);
        ClientManager.joinTag(PushGroup.GAME_GROUP, string2, TAG);

        ReentrantLock lock = LooksManager.getWriteLock(Game.class, anchorInfoId1);
        ReentrantLock lock1 = LooksManager.getWriteLock(Game.class, anchorInfoId2);
        lock.lock();
        lock1.lock();
        try {
            Game game1 = gameDao.findByIdMust(anchorInfoId1);
            Game game2 = gameDao.findByIdMust(anchorInfoId2);
            game1.setType(2);
            game2.setType(2);
            gameDao.save(game1);
            gameDao.save(game2);


            PVP value = new PVP(anchorInfoId1, anchorInfoId2);

            if (PVPInfoData.containsKey(value.hashCode())) {
                throw new RuntimeException("战斗已存在");
            }
            PVPInfoData.put(value.hashCode(), value);

            ClientManager.sendMessageToClient(PushGroup.GAME_GROUP, value, TAG);
        } finally {
            lock.unlock();
            lock1.unlock();
        }
    }

    @EqualsAndHashCode(exclude = {"userInfoIdSeat1", "userInfoIdSeat2"})
    public static class PVP {
        public Integer anchorInfoId1;
        Map<Integer, String> userInfoIdSeat1;
        public Integer anchorInfoId2;
        Map<Integer, String> userInfoIdSeat2;

        public PVP(Integer anchorInfoId1, Integer anchorInfoId2) {
            this.anchorInfoId1 = anchorInfoId1;
            this.anchorInfoId2 = anchorInfoId2;

            Game game1 = gameDao.findByIdMust(anchorInfoId1);
            Game game2 = gameDao.findByIdMust(anchorInfoId2);
            this.userInfoIdSeat1 = game1.userInfoIdSeat;
            this.userInfoIdSeat2 = game2.userInfoIdSeat;
        }
    }
}
